/**
 * 认证状态管理
 * 创建时间：2025-09-11
 * 作者：开发团队
 * 目的：管理用户认证状态和用户信息
 */

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { authApi } from '@/api/auth'
import type { User, LoginRequest } from '@/types/auth'
import router from '@/router'

export const useAuthStore = defineStore('auth', () => {
  // 状态定义
  const token = ref<string | null>(localStorage.getItem('token'))
  const user = ref<User | null>(null)
  const isLoading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const userRole = computed(() => user.value?.role)
  const userName = computed(() => user.value?.name || '')
  const userPermissions = computed(() => user.value?.permissions || [])

  // 动作方法
  
  /**
   * 用户登录
   * :param loginData: 登录表单数据
   * :return: 登录是否成功
   */
  const login = async (loginData: LoginRequest): Promise<boolean> => {
    try {
      isLoading.value = true
      const response = await authApi.login(loginData)
      
      // 保存token和用户信息
      token.value = response.token
      user.value = response.user
      localStorage.setItem('token', response.token)
      
      // 记住密码功能
      if (loginData.remember) {
        localStorage.setItem('remembered_username', loginData.username)
      } else {
        localStorage.removeItem('remembered_username')
      }
      
      return true
    } catch (error) {
      console.error('登录失败:', error)
      return false
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 用户登出
   */
  const logout = async (): Promise<void> => {
    try {
      if (token.value) {
        await authApi.logout()
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除本地状态
      token.value = null
      user.value = null
      localStorage.removeItem('token')
      
      // 跳转到登录页
      router.push('/login')
    }
  }

  /**
   * 获取用户信息
   */
  const fetchUserInfo = async (): Promise<void> => {
    try {
      if (!token.value) return
      
      const userInfo = await authApi.getProfile()
      user.value = userInfo
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能token已过期
      await logout()
    }
  }

  /**
   * 刷新token
   */
  const refreshToken = async (): Promise<boolean> => {
    try {
      const response = await authApi.refreshToken()
      token.value = response.token
      localStorage.setItem('token', response.token)
      return true
    } catch (error) {
      console.error('刷新token失败:', error)
      await logout()
      return false
    }
  }

  /**
   * 检查权限
   * :param permission: 权限字符串
   * :return: 是否有权限
   */
  const hasPermission = (permission: string): boolean => {
    return userPermissions.value.includes(permission)
  }

  /**
   * 检查角色
   * :param roles: 角色数组
   * :return: 是否有对应角色
   */
  const hasRole = (roles: string[]): boolean => {
    return !!userRole.value && roles.includes(userRole.value)
  }

  /**
   * 获取记住的用户名
   */
  const getRememberedUsername = (): string => {
    return localStorage.getItem('remembered_username') || ''
  }

  /**
   * 初始化认证状态
   */
  const initAuth = async (): Promise<void> => {
    if (token.value) {
      await fetchUserInfo()
    }
  }

  return {
    // 状态
    token,
    user,
    isLoading,
    
    // 计算属性
    isAuthenticated,
    userRole,
    userName,
    userPermissions,
    
    // 方法
    login,
    logout,
    fetchUserInfo,
    refreshToken,
    hasPermission,
    hasRole,
    getRememberedUsername,
    initAuth
  }
})
